package com.zaoqi.service.impl;

import com.zaoqi.pojo.CameraData;
import com.zaoqi.pojo.Device;
import com.zaoqi.repository.CameraDataRepository;
import com.zaoqi.repository.DeviceRepository;
import com.zaoqi.service.CameraDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class CameraDataServiceImpl implements CameraDataService {
    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private CameraDataRepository cameraDataRepository;
    @Autowired
    private RestTemplate restTemplate;

    private static final String LOGIN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";
    private static final String CAMERA_CAPTURE_URL = "https://open.ys7.com/api/lapp/device/capture";
    private static final String ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e"; // 示例账号
    private Device findDeviceBySerialNumber(String serialNumber) {
        return deviceRepository.findBySerialNumber(serialNumber)
                .orElseThrow(() -> new IllegalArgumentException("Device not found for serial number: " + serialNumber));
    }

    @Override
    public CameraData captureAndSaveCameraImage(String serialNumber) {
        // 获取 accessToken
        String accessToken = getAccessToken();
        if (accessToken == null) {
            return null;
        }

        // 调用接口获取图片 URL
        String picUrl = captureCameraImage(serialNumber, accessToken);

        if (picUrl != null) {
            CameraData cameraData = new CameraData();

            // 根据 serialNumber 获取 Device 实体
            Device device = findDeviceBySerialNumber(serialNumber);
            cameraData.setDevice(device);
            cameraData.setPhotoUrl(picUrl); // 设置图片 URL
            cameraData.setCreatedAt(LocalDateTime.now());

            return cameraDataRepository.save(cameraData); // 保存数据到数据库
        }
        return null;
    }


    @Override
    public String captureCameraImage(String serialNumber, String accessToken) {
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 构建请求体
        Map<String, String> params = new HashMap<>();
        params.put("accessToken", accessToken);
        params.put("deviceSerial", serialNumber); // 使用 serialNumber
        params.put("channelNo", "1"); // 通道号，通常为 1
        params.put("quality", "1");  // 清晰度，1 表示高清

        // 转换为 HttpEntity
        StringBuilder requestBody = new StringBuilder();
        params.forEach((key, value) -> requestBody.append(key).append("=").append(value).append("&"));
        String body = requestBody.toString();
        body = body.substring(0, body.length() - 1); // 去掉末尾的 "&"

        HttpEntity<String> entity = new HttpEntity<>(body, headers);

        // 发起请求
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(CAMERA_CAPTURE_URL, HttpMethod.POST, entity, String.class);
            String responseBody = responseEntity.getBody();

            // 从返回的 JSON 中提取图片 URL
            if (responseBody != null && responseBody.contains("picUrl")) {
                return extractPicUrl(responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private String extractPicUrl(String responseBody) {
        // 从 JSON 响应中提取 picUrl
        int start = responseBody.indexOf("\"picUrl\":\"") + 10;
        int end = responseBody.indexOf("\"", start);
        return start > 0 && end > start ? responseBody.substring(start, end) : null;
    }

    @Override
    public String getAccessToken() {
        // 构建请求体，传递 accountId
        String requestBody = "{\"accountId\":\"" + ACCOUNT_ID + "\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        // 发起请求获取 accessToken
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(LOGIN_URL, HttpMethod.POST, entity, String.class);
            String responseBody = responseEntity.getBody();
            if (responseBody != null && responseBody.contains("accessToken")) {
                int start = responseBody.indexOf("\"accessToken\":\"") + 15;
                int end = responseBody.indexOf("\"", start);
                return start > 0 && end > start ? responseBody.substring(start, end) : null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
